//
//  ViewController.m
//  07-线程安全-互斥锁-线程同步
//
//  Created by J on 16/2/24.
//  Copyright © 2016年 J. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

//售票员1
@property(nonatomic,strong)NSThread* thread01;
@property(nonatomic,strong)NSThread* thread02;
@property(nonatomic,strong)NSThread* thread03;
@property(nonatomic,assign)NSInteger ticketsCount;
@property(nonatomic,strong)NSObject *lock;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.ticketsCount = 100;
    self.thread01 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.thread01.name = @"售票员01";
    
    self.thread02 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.thread02.name = @"售票员02";

    self.thread03 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.thread03.name = @"售票员03";
    self.lock = [NSObject new];

}

- (void)saleTicket{
//    @synchronized(self.lock){//不能加外面 不然就等于一个售票员卖完了其他线程才能进入
    while (1) {
        //synchronized 线程同步 默认是线程异步 同步不是指同时执行 指的是同一条线上执行 多条线程在同一条线上执行(按照顺序执行)类似于串行队列
        @synchronized(self.lock) {//这里的对象不能每次都是一个新的必须是同一个对象 在方法外面定义一个对象如果对象在里面定义每个线程调用一次就新建一个对象就不是同一把锁了 //锁对象只能用同一个 只要是个对象就行 也可以直接传self 多条线程同时访问一个变量需要数据操作的时候才加锁
        
            NSInteger count = self.ticketsCount;//取出总数
            //        NSLock *lock = [[NSLock alloc]init];
            //        [lock lock];
            if (count) {
                self.ticketsCount = count-1;
                
                NSLog(@"%@卖了一张票,剩下:%zd张",[NSThread currentThread].name,self.ticketsCount);
                
            }else{
                NSLog(@"票卖完了");
                break;
            }
            //        [lock unlock];
        }

    }
   

//    }
    
}




- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.thread01 start];
    [self.thread02 start];
    [self.thread03 start];

}

@end
